<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%String skin = (String) session.getAttribute("USERSKIN_SESSION");%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>档案保管</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <jsp:include page="/inc/head.jsp" flush="true"/>
    <style>

        @media  screen and (max-width:1440px) {
            #formSearch .form-group {
                margin-bottom: 10px;
            }
        }
        .bootstrap-table .icon-refresh {
            padding: 3px 0;
        }
    </style>
</head>
<body>
<div class="panel-body">
    <div class="panel panel-default">
        <div class="panel-heading">查询条件</div>
        <div class="panel-body">
            <form id="formSearch" class="form-inline" role="form">
                <div class="form-group">
                    <label for="txt_volTitle">题名</label>
                    <input type="text" class="form-control" id="txt_volTitle" style="width: 400px;"/>
                </div>
                <div class="form-group volShow">
                    <label for="txt_volNO">&nbsp;&nbsp;&nbsp;&nbsp;案卷号</label>
                    <input type="text" class="form-control" id="txt_volNO" style="width: 100px;"/>
                </div>
                <div class="form-group">
                    <label cfor="sin_itemType">&nbsp;&nbsp;&nbsp;&nbsp;案件类型</label>
                    <select id="sin_itemType" class="form-control">
                    </select>
                </div>
                <div class="form-group">
                    <label for="txt_volStoragelocation">&nbsp;&nbsp;&nbsp;&nbsp;存放位置</label>
                    <input title="dfg" type="text" class="form-control" id="txt_volStoragelocation" style="width: 300px;"/>
                </div>
                <div class="form-group">
                    <button type="button" style="margin-left:30px" id="btn_query" onclick="queryParams()"
                            class="btn btn-primary">查询
                    </button>
                    <button type="button" style="margin-left:10px" id="btn_clean" onclick="queryParamsSinCleanKeep()"
                            class="btn btn-default">重置
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div id="toolbar" class="btn-group">
        <shiro:hasPermission name="cms:storage:location">
        <button id="insertBoxAndLocation" type="button" class="btn btn-default" onclick="updateBoxAndLocation()">
            <span class="glyphicon glyphicon-folder-close" aria-hidden="true"></span> 设置盒号及存放位置
        </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="cms:storage:print">
        <div class="btn-group" id="btn-sprint">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                打印<span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu">
                <li><a id="printPrepar" onclick="printPreparAction()" href="javascript:;">备考表</a></li>
                <li><a id="printVolumeFixed" onclick="printVolumeFixedAction()" href="javascript:;">卷内目录(模板)</a></li>
                <li><a id="printVolumeDirectory" onclick="printVolumeDirAction()" href="javascript:;">卷内目录(自定义)</a></li>
            </ul>
        </div>
        </shiro:hasPermission>
        <shiro:hasPermission name="cms:storage:return">
        <button id="btn_turnDown" type="button" class="btn btn-default" onclick="updateAction2()">
            <span class="glyphicon glyphicon-repeat" aria-hidden="true"></span> 驳回
        </button>
        </shiro:hasPermission>
        <div class="btn-group">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                类型选择<span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu">
                <li><a id="NotArchive" onclick="SearchArcStoragePage()" href="javascript:;">传统案卷</a></li>
                <li><a id="returnArchived" onclick="SingleArchItemAction()" href="javascript:;">单件案卷</a></li>
            </ul>
        </div>
    </div>
    <table id="table"></table>
</div>
<!-- 记录生成pdf文件名的毫秒数 -->
<input type="hidden" id="nowMilliseconds" name="nowMilliseconds">
<!-- 记录当前选择的是传统案卷还是单件 0:传统案卷,1:单件案卷-->
<input type="hidden" id="tradOrSinRecord" name="tradOrSinRecord" value="0" >
<%--存放载体类型--%>
<input type="hidden" id="volCarrier" name="volCarrier">
    <jsp:include page="/inc/footer.jsp" flush="true"/>
    <script src="${basePath}/js/devPublic.js"></script>
    <jsp:include page="/WEB-INF/jsp/preArchive/viewOriginal.jsp" flush="true"/>
    <jsp:include page="/WEB-INF/jsp/preArchive/print.jsp" flush="true"/>
    <jsp:include page="/WEB-INF/jsp/preArchive/printPdf.jsp" flush="true"/>
</section>
<script>
    var $table = $('#table');
    $(function () {
        bootstrapTableAction();
        //y隐藏单件类型查询条件
        $(".volShow").show();
        //禁用/启动功能
        enableSomeTools();
        findAllJudTypeSiNArch();
    });
    function bootstrapTableAction() {
        $table.bootstrapTable({
            url: '${basePath}/pcwindow/keep/keepVolList',//请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortOrder: "desc",                   //排序方式
            queryParams: "volDefaultParams",
           // queryParams: queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 25,                       //每页的记录行数（*）
            pageList: [25, 50, 100],        //可供选择的每页的行数（*）
            //search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            //strictSearch: true,
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            // height: 700,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "volId",                     //每一行的唯一标识，一般为主键列
            //showToggle:true,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: true,                   //是否显示父子表
            columns: [
                {field: 'ck', checkbox: true},
                {field: 'volId', title: '卷ID', visible:false},
                {field: 'volClass', title: '案卷类型',formatter: 'typeKeepFormatter'},
                {field: 'volStorageTime', title: '保管期限',formatter: 'storageTimeFormatter'},
                {field: 'volNo', title: '案卷号',sortable: true},
                {field: 'volFian', title: '全宗号', visible:false},
                {field: 'volTitle', title: '案卷题名'},
                {field: 'volArchiveYear', title: '归档年度',sortable: true},
                {field: 'volArchiveUnit', title: '归档单位',formatter: 'orgIdConversionNameKeepFormatter', visible:false},
                {field: 'volAuditLeader', title: '审计组长', visible:false},
                {field: 'volAuditDate', title: '审计起止日期', visible:false},
                {field: 'volSecret', title: '密级',formatter: 'traKeepFormatter', visible:false},
                {field: 'volStr3', title: '保密年限', visible:false},
                {field: 'volInsideDate', title: '卷内起止日期', visible:false},
                {field: 'volTotal', title: '总卷数', visible:false},
                {field: 'volCurrent', title: '当前卷数', visible:false},
                {field: 'volCaseNum', title: '档号'},
                {field: 'volBoxNumber', title: '盒号'},
                {field: 'volStoragelocation', title: '存放位置'},
                {field: 'volTotalPage', title: '页数', visible:false},
                {field: 'volItemNumber', title: '件数',visible:false},
                {field: 'volPublicStatus', title: '是否公开',formatter: 'publicStatusFormatter' },
                {field: 'volCarrier', title: '载体类型', formatter: 'carrierStatusFormatter' },
                {field: 'volStatus', title: '案卷状态', visible: false,formatter: 'volStatusArcFormatter' },
                {field: 'createdat', title: '创建时间',formatter:'createdatAction', visible:false},
                {field: 'action', title: '操作', align: 'center', formatter: 'actionFormatter', events: 'actionEvents', clickToSelect: false}
            ],
            //注册加载子表的事件。注意下这里的三个参数！
            onExpandRow: function (index, row, $detail) {
                itemTableAction(index, row, $detail);
            },
            onLoadSuccess:function(data){
                //无数据隐藏分页
                if(data && data.total == 0){
                    $('.fixed-table-pagination').hide()
                }
            }
        });
    }
    /**
     * 初始化子表格(无限循环)
     */
    function itemTableAction(index, row, $detail){
        var volCarrier = row.volCarrier;
        $("#volCarrier").val(volCarrier);
        var parentid = row.volId;
        var $child_table = $detail.html('<table  id="child_table"></table>').find('table');
        $child_table.bootstrapTable({
            url: '${basePath}/pcwindow/item/itemList',
            method: 'get',
            queryParams: { strParentID: parentid },
            //ajaxOptions: { strParentID: parentid },
            clickToSelect: false,
            detailView: false,//父子表
            uniqueId: "itemId",
            dataType:'json',
            pagination: false,
            /* sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
             pageNumber:1,                       //初始化加载第一页，默认第一页
             pageSize: 10,                       //每页的记录行数（*）
             pageList: [10, 25, 50, 100],*/        //可供选择的每页的行数（*）
            cardView: false,                    //是否显示详细视图
            showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            showColumns: true,                  //是否显示所有的列
            columns: [
                /* {field: 'ck',checkbox: true},*/
                {field: 'itemNum', title: '序号'},
                {field: 'itemName',title: '文号'},
                {field: 'itemTemporary',title: '单元号', visible:false},
                {field: 'itemSecret',title: '卷内件密级',formatter: 'traItemKeepFormatter', visible:false},
                {field: 'itemTitle',title: '卷内件题名'},
                {field: 'itemRespons',title: '责任者'},
                {field: 'itemCreateTime',title: '发文日期'},
                {field: 'itemPage',title: '页次', visible:false},
                {field: 'itemStr1',title: '件号', visible:false},
                {field: 'itemStr5', title: '是否公开', visible: false,formatter: 'publicStatusFormatter' },
                {field: 'itemStr3',title: '挂接状态', formatter: 'statusFormatter',width:'100px',align:"center"},
                {field: 'itemCreateDate',title: '创建时间',formatter:'createItemAction', visible:false},
                {field: 'action', title: '操作', align: 'center', formatter: 'sonFormatter', events: 'sonEvents', clickToSelect: false}
            ]

        });
    }
    //父表格式化操作按钮
    function actionFormatter(value, row, index) {
        return '<a href="javascript:void(0)" style="color:#01579b;" onclick="moveInItemAction(' + row.volId+')" >移入件</a>'
    }

    //子表操作按钮

    function sonFormatter(value, row, index) {
        return '<a href="javascript:void(0)" style="color:#01579b;" onclick="detailAction(' + row.itemId+')" >原文</a>';
    }

    function moveInItemAction(volId) {
        window.location.href = "${basePath}/pcwindow/arcCreate?volIdToDetils="+volId+"&position=storage";
    }

    //格式化归档单位
    function orgIdConversionNameKeepFormatter(value, row, index){
        return orgList[value];
    }
    //格式化期限
    function storageTimeFormatter(value, row, index){
        return storageTime[value];
    }

    //载体类型
    function carrierStatusFormatter(value, row, index) {
        if (value == '0') {
            return '<span class="label label-warning">仅实体</span>';
        } else if(value == '1'){
            return '<span class="label label-info">仅电子</span>';
        }else {
            return '<span class="label label-success">共存</span>';
        }
    }

    function volStatusArcFormatter(value, row, index){
        if (value == '0') {
            return '<span>正常</span>';
        } else if(value == '1'){
            return '<span>鉴定中</span>';
        } else if(value == '2'){
            return '<span>借阅中</span>';
        } else if(value == '3'){
            return '<span>已移出</span>';
        } else if(value == '8'){
            return '<span>销毁</span>';
        } else if(value == '9'){
            return '<span>删除</span>';
        }else {
            return '<span>其它</span>';
        }
    }

    function itemStatusArcFormatter(value, row, index){
        if (value == '0') {
            return '<span>正常</span>';
        } else if(value == '1'){
            return '<span>鉴定中</span>';
        } else if(value == '2'){
            return '<span>借阅中</span>';
        } else if(value == '3'){
            return '<span>已移出</span>';
        } else if(value == '8'){
            return '<span>销毁</span>';
        }else {
            return '<span>其它</span>';
        }
    }

    //是否公开
    function publicStatusFormatter(value, row, index){
        if (value == '0') {
            return '<span class="label label-warning">未公开</span>';
        } else{
            return '<span class="label label-info">公开</span>';
        }
    }

    /**
     * 格式化卷密级
     * @param value
     * @param row
     * @param index
     */
    function traKeepFormatter(value, row, index) {
        return secretLevel[value];
    }
    /**
     * 格式化件密级
     * @param value
     * @param row
     * @param index
     */
    function traItemKeepFormatter(value, row, index) {
        return secretLevel[value];
    }

    /**
     * 类型
     */
    function typeKeepFormatter(value, row, index){
        return archiveType[value];
    }

    //初始化时间
    function timeFormatter(value, row, index) {
        return formatshortDateTime(value);
    }

    function updateBoxAndLocation(){
        var rows = $table.bootstrapTable('getSelections');
        var tradOrSinRecord2= $("#tradOrSinRecord").val();
        if (rows.length == 0){
            $.confirm({
                title: false,
                content: '请选择一条或者多条记录！',
                autoClose: 'cancel|3000',
                backgroundDismiss: true,
                buttons: {
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        } else {
            var biaoshi = 0;
            for(var i=0;i<rows.length; i++){
                if(tradOrSinRecord2 == "0"){
                    if(rows[i].volStoragelocation != '' && rows[i].volStoragelocation != null){
                        biaoshi = 1;
                        break;
                    }
                }else {
                    if(rows[i].itemStoragelocation != '' && rows[i].itemStoragelocation != null){
                        biaoshi = 1;
                        break;
                    }
                }
            }
            if(biaoshi == 1){
                $.confirm({
                    title: false,
                    content: '选择项中已有存储位置，是否确定编辑！',
                    autoClose: 'cancel',
                    backgroundDismiss: true,
                    buttons: {
                        ok:{
                            text: '确定',
                            btnClass: 'waves-effect waves-button',
                            action:function () {
                                updateAction();
                            }
                        },
                        cancel: {
                            text: '取消',
                            btnClass: 'waves-effect waves-button'
                        }
                    }
                });
            }else{
                updateAction();
            }
        }
    }
    //修改盒编号和存储位置
    var updateDialog;
    function updateAction() {
        updateDialog = $.dialog({
            animationSpeed: 300,
            title: '设置盒号及存储位置',
            content: 'url:${basePath}/manage/keep/update',
            onContentReady: function () {
                initMaterialInput();
            }
        });
    }

    var params={
        volTitle: $("#txt_volTitle").val(),
        volNO: $("#txt_volNO").val(),

        volStoragelocation:$("#txt_volStoragelocation").val()
    };
    var opt = {
        url: '${basePath}/pcwindow/keep/keepVolList',
        silent: true,
        query:params
    };

    /**
     * 重置查询条件
     */
    function queryParamsSinCleanKeep() {
        $("#txt_volTitle").val("");
        $("#txt_volNO").val("");
        $("#txt_volStoragelocation").val("");
        $("#sin_itemType").empty();
        findAllJudTypeSiNArch();
    }

    /**
     * 案卷驳回
     */
    function updateAction2() {
       var tradOrSinRecord= $("#tradOrSinRecord").val();
        var rows = $table.bootstrapTable("getSelections");

        if(rows.length == 0){
            $.alert("请选中至少一行执行此操作");
            return;
        }
        var url;
        var data;
        var noPushStr="";

        if(tradOrSinRecord=="1"){
            url="${basePath}/manage/keep/sinRefuse";
            var ids = new Array();
            var noPushItem= new Array();
            for (var i in rows) {
                if(rows[i].itemStatus !="0" || rows[i].itemStatus!=0){
                    noPushItem.push(rows[i].itemStr1)
                }else {
                    ids.push(rows[i].itemId);
                }
            }
            data={itemIds:ids.join("-")};
            noPushStr=noPushItem.join("，");
        }else {
            url="${basePath}/manage/keep/refuse";
            var ids = new Array();
            var noPushVol= new Array();
            for (var i in rows) {
                if(rows[i].volStatus !="0" || rows[i].volStatus!=0){
                    noPushVol.push(rows[i].volCaseNum)
                }else {
                    ids.push(rows[i].volId);
                }
            }
            data={volIds:ids.join("-")};
            noPushStr=noPushVol.join("，");
        }
        var content="是否确定驳回案卷？"
        if(noPushStr !="" && noPushStr!=null){
            content=noPushStr+"正在利用中无法驳回，是否继续驳回其它案卷？";
        }

        $.confirm({
            title: false,
            content: content,
            autoClose: 'cancel',
            backgroundDismiss: true,
            buttons: {
                ok:{
                    text: '确定',
                    btnClass: 'waves-effect waves-button',
                    action:function () {
                        $.ajax({
                            type:"post",
                            url:url,
                            data:data,
                            success:function (result) {
                                if(result == "success"){
                                    $.alert("驳回成功");
                                    $table.bootstrapTable("refresh");
                                    if(tradOrSinRecord=="1"){
                                        SingleArchItemAction();
                                    }else {
                                        SearchArcStoragePage();
                                    }
                                }else{
                                    $.alert("驳回失败，请重试");
                                }
                            },
                            error:function(){
                                $.alert("未知原因，请刷新系统重试");
                            }
                        })
                    }
                },
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    }

    function volDefaultParams(){
        return {
            volTitle: $("#txt_volTitle").val(),
            volNO: $("#txt_volNO").val(),
            sin_itemType:$("#sin_itemType").find(":selected").val(),
            volStoragelocation:$("#txt_volStoragelocation").val(),
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order}
    }

    /**
     * 条件查询
     */
    function queryParams() {
        var tradOrSinRecord= $("#tradOrSinRecord").val();
        var url;
        var data;
        if(tradOrSinRecord=="0"){
            /*data={
                volTitle: $("#txt_volTitle").val(),
                volNO: $("#txt_volNO").val(),
                sin_itemType:$("#sin_itemType").find(":selected").val(),
                volStoragelocation:$("#txt_volStoragelocation").val()
            };*/
            url='${basePath}/pcwindow/keep/keepVolList';
        }else {
            /*data={
                sin_itemTitle: $("#txt_volTitle").val(),
                sin_itemType:$("#sin_itemType").find(":selected").val(),
                sin_Storagelocation:$("#txt_volStoragelocation").val(),
                sinStatus:'1'
            };*/
            url='${basePath}/pcwindow/sin/itemSinList?sinStatus=1';
        }
        var optquery = {
            url: url,
            silent: true
            //query:data
        };
        $table.bootstrapTable('refresh', optquery);
    }

    /**
     * 卷时间处理
     */
    function createdatAction(value, row, index) {
        var timeVol = row.volCreateDate;
        if(timeVol!=null&&timeVol!=''){
            return formatshortDateTime(timeVol);
        }
        return formatshortDateTime("-");
    }
    /**
     * 卷宗状态
     */
    function statusVolumeFormatter(value, row, index){
        if (value == '0') {
            return '<span class="label label-success">新著录</span>';
        }else if(value == '3'){
            return '<span class="label label-info">已驳回</span>';
        }else {
            return '<span class="label label-info">未知</span>';
        }
    }
    /**
     * 跳转原文页面
     */
    function detailAction(id){
        if(id !="" && id !=null){
            $.ajax({
                type: "post",
                url: "${basePath}/pcwindow/item/viewItemOriginal",
                data: { id: id },
                success: function (data) {
                    if (data != "failure") {
                        $('#openPdfModel').modal({
                            keyboard: true
                        });

                        var url=data;
                        var str = url.substr(url.length-4,url.length-1);
                        if(str==".jpg" || str==".png"){
                            var htmlImg = '<img src="'+url+'" style=" width:100%;height: 100%;" alt="预览">';
                            $("#pdfDialog").eq(0).append(htmlImg);
                        }else{
                            var options={
                                pdfOpenParams: {
                                    pagemode: "thumbs",
                                    navpanes: '0',
                                    /*toolbar: '0',*/   //去掉工具栏,打印,下载等,,,,
                                    statusbar: '0',
                                    view: 'FitV'
                                }};
                            var myPDF = PDFObject.embed(url, "#pdfDialog", options);
                        }
                    }else {
                        Ewin.alert("获取原文失败!");
                    }
                },
                error: function () {
                    Ewin.alert('加载错误,请联系管理员!');
                }
            })
        }else{
            Ewin.alert('请选择数据!');
        }
    }
    // 格式化状态
    function statusFormatter(value, row, index) {
        var volCarrier = $("#volCarrier").val();
        if(volCarrier == 0){
            return '<span class="label label-default">-</span>';
        }else{
            if (value == '1') {
                return '<span class="label label-success">已上传</span>';
            }else {
                return '<span class="label label-info">未上传</span>';
            }
        }
    }
    /**
     * 件时间处理
     */
    function createItemAction(value, row, index){
        var timeItem = value.time;
        if(timeItem=="undefined" || timeItem==undefined){
            timeItem=value;
        }
        if(timeItem!=null&&timeItem!=''){
            return formatshortDateTime(timeItem);
        }
        return formatshortDateTime("-");
    }

    //*************************************打印操作**************************************
    /**
     * 打印卷内目录(自定义)
     */
    function printVolumeDirAction(){
        var rows = $table.bootstrapTable('getSelections');
        if (rows.length != 1) {
            confirmEvent('请选择一条记录！');
        } else {
            $("#printTable tbody").empty();
            $("#printVolumeDirModal").modal("show");
            $("#printVolumeTitle").text("请选择打印项：");
            autoPrintTable();
        }
    }

    //自动生成两列：顺序号，题名
    function autoPrintTable(){
        var defaultNum = 4;
        for (var i=1;i<parseInt(defaultNum);i++){
            $("#printTable tbody").append(
                "<tr>"+
                "<td style=\"text-align: center\" class=\"Columns\">"+i+"</td>"+
                "<td><select  style='width: 100%;height: 100%'></select></td>"+
                "<td><a class=\"delPrint\" href=\"javascript:;\" onclick=\"deletePrintAction(this)\" data-toggle=\"tooltip\" title=\"删除\"><i class=\"glyphicon glyphicon-remove\"></i></a></td>"+
                "</tr>"
            );
            //给下拉框中添加<option>
            var row = $("#printTable tr:last").find("select:eq(0)");
            row.append(printSelectValue);
            //设置1,2列的默认选项
            switch (i){
                case 1:
                    row.find("option[value = 'itemNum']").attr("selected","selected");
                    break;
                case 2:
                    row.find("option[value = 'itemPage']").attr("selected","selected");
                    break;
                case 3:
                    row.find("option[value = 'itemTitle']").attr("selected","selected");
                    break;
                default:
                    break;
            }
        }
    }
    //下拉框中的<option>
    var printSelectValue=function (){
        var secretStr = "";
        for(var key in printFields){
            secretStr += "<option value="+printFields[key].value+">"+printFields[key].text+"</option>";
        }
        return $(secretStr);
    }

    //添加一行
    function insertRowPrint(){
        var comns;
        var lieshu= $("#printTable tr:last td:first").text();
        if(lieshu.length == 0){
            comns=parseInt(1);
        }else{
            comns=parseInt(lieshu)+1;
        }

        $("#printTable tbody").append(
            "<tr>"+
            "<td style=\"text-align: center\" class=\"Columns\">"+comns+"</td>"+
            "<td><select  style='width: 100%;height: 100%'></select></td>"+
            "<td><a class=\"delPrint\" href=\"javascript:;\" onclick=\"deletePrintAction(this)\" data-toggle=\"tooltip\" title=\"删除\"><i class=\"glyphicon glyphicon-remove\"></i></a></td>"+
            "</tr>"
        );
        //给下拉框中添加<option>
        var row = $("#printTable tr:last").find("select:eq(0)");
        row.append(printSelectValue);
    }
    //删除本行
    function deletePrintAction(obj){
        $(obj).parents('tr').remove();//删除选择的该行
        $('#printTable tbody tr').each(function(i){  // 遍历 tr
            $(this).find("td:first").text(i+1);
        });
    }
    //生成卷内目录
    function printSubmitAction() {
        //获取打印设置框的值
        var allPrintNum = new Array();
        $('#printTable tbody tr').each(function(i){  // 遍历 tr
            var columns=$(this).find("td:first").text();//列
            var fieldsValue=$(this).find("select:first").find(":selected").val();//表名
            var fieldsText=$(this).find("select:first").find(":selected").text();//对应中文
            var contents=columns+"|"+fieldsValue+"|"+fieldsText;
            allPrintNum.push(contents);
        });
        //获取列表中勾选的卷
        var rowsPrint = $table.bootstrapTable('getSelections');
        var volIdPrint=rowsPrint[0].volId;

        if(allPrintNum.length != 0){
            var allPrintRows=JSON.stringify(allPrintNum);
            printAjaxAction(allPrintRows,volIdPrint);
            $("#printVolumeDirModal").modal('hide');
        }
    }

    //生成卷内目录ajax请求后台
    function printAjaxAction(printRows,volIdPrint){
        $.ajax({
            type: 'post',
            url: '${basePath}/pcwindow/print/printRowsGen',
            data: {printRows:printRows,volIdPrint:volIdPrint},
            async:true,
            // contentType:"application/json", // 指定这个协议很重要
            beforeSend: function() {
                // 禁用按钮防止重复提交
                $("#printSubmitId").attr({ disabled: "disabled" });
            },
            success: function(result) {
                //alert("生成卷内目录成功，展示pdf");
                if(result.code == 0){
                    confirmEvent('操作失败，请重试！');
                }else{

                    var options={
                        pdfOpenParams: {
                            pagemode: "thumbs",
                            navpanes: '0',
                            /*toolbar: '0',*/   //去掉工具栏,打印,下载等,,,,
                            statusbar: '0',
                            view: 'FitV'
                        }};
                    $('#pdfViewModel').modal({
                        keyboard: true
                    });
                    var myPDF = PDFObject.embed(result.data, "#pdfShow", options);
                    $("#nowMilliseconds").val(result.data);
                }
            },
            complete: function () {
                $("#printSubmitId").removeAttr("disabled");
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                confirmEvent(textStatus);
            }
        });
    }

    /**
     * 捕获openPdfModel，pdf打印窗口关闭事件
     */
    $(function () {
        $('#pdfViewModel').on('hide.bs.modal', function () {
            var openMilliseconds=$("#nowMilliseconds").val();
            $.ajax({
                type: 'post',
                url: '${basePath}/pcwindow/print/delOpenPdf',
                data: {openMilliseconds:openMilliseconds},
                // contentType:"application/json", // 指定这个协议很重要
                success: function(result) {
                    if(result.code == 1){
                        $("#nowMilliseconds").val("");
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    confirmEvent(textStatus);
                }
            });

        });
    });

    /**
     * 打印卷内目录(固定模板)
     */
    function printVolumeFixedAction() {
        var rows = $table.bootstrapTable('getSelections');
        if (rows.length != 1) {
            confirmEvent('请选择一条记录！');
        } else {
            $.ajax({
                type: 'post',
                url: '${basePath}/pcwindow/print/printVolumeFixed',
                data: {volId:rows[0].volId},
                async:true,
                // contentType:"application/json", // 指定这个协议很重要
                success: function(result) {
                    if(result.code == 0){
                        confirmEvent('操作失败，请重试！');
                    }else{

                        var options={
                            pdfOpenParams: {
                                pagemode: "thumbs",
                                navpanes: '0',
                                /*toolbar: '0',*/   //去掉工具栏,打印,下载等,,,,
                                statusbar: '0',
                                view: 'FitV'
                            }};
                        $('#pdfViewModel').modal({
                            keyboard: true
                        });
                        var myPDF = PDFObject.embed(result.data, "#pdfShow", options);
                        $("#nowMilliseconds").val(result.data);
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    confirmEvent(textStatus);
                }
            });
        }
    }

    /**
     * 打印备考表
     */
    function printPreparAction(){
        confirmEvent("模板样式未定义,待定义!");
    }

    //********************************************打印结束**********************************

    //禁用一些功能
    function disableSomeTools(){
        $("#btn-sprint").hide();
    }
    //启动一些功能
    function enableSomeTools(){
        $("#btn-sprint").show();
    }

    //查询传统案卷
    function SearchArcStoragePage() {
        $(".volShow").show();
        enableSomeTools();
        $table.bootstrapTable('destroy');;//清空以前的表格
        bootstrapTableAction()
        $("#tradOrSinRecord").val("0");

    }

    //更换单件列表
    function SingleArchItemAction(){
        $(".volShow").hide();
        //禁用功能
        disableSomeTools();
        $("#tradOrSinRecord").val("1");
        $table.bootstrapTable('destroy');;//清空以前的表格
        var url='${basePath}/pcwindow/sin/itemSinList?sinStatus='+1;
        var columns=[
            {field: 'ck',checkbox: true},
            {field: 'itemId', title: '单件ID', visible:false},
            {field: 'itemNum',title: '保管期限'},
            {field: 'itemName',title: '文号'},
            {field: 'itemTemporary',title: '单元号', visible:false},
            {field: 'itemSecret',title: '密级',formatter: 'secretLevelKeepFormatter', visible:false},
            {field: 'itemExp4',title: '保密年限', visible:false},
            {field: 'itemExp1',title: '文件类型',formatter:'typeKeepFormatter'},
            {field: 'itemExp2',title: '归档单位',formatter: 'orgIdConversionNameKeepFormatter'},
            {field: 'itemExp3',title: '归档年度',sortable: true},
            {field: 'itemTitle',title: '题名'},
            {field: 'itemRespons',title: '责任者'},
            {field: 'itemCreateTime',title: '发文日期'},
            {field: 'itemFian',title: '全宗号'},
            {field: 'itemBoxNumber',title: '盒号'},
            {field: 'itemStoragelocation',title: '存放位置'},
            {field: 'itemStr1',title: '件号', visible:false},
            {field: 'itemStr4',title: '著录人', visible:false},
            {field: 'itemArcPerson',title: '归档责任人', visible:false},
            {field: 'itemStr1Date',title: '归档时间', visible:false,formatter:'timeFormatter'},
            {field: 'itemPage',title: '页数', visible:false},
            {field: 'itemPublicStatus', title: '是否公开', visible: false,formatter: 'publicStatusFormatter' },
            { field: 'itemCarrier', title: '载体类型', visible: false,formatter: 'carrierStatusFormatter' },
            { field: 'itemStatus', title: '单件状态', visible: false,formatter: 'itemStatusArcFormatter' },
            {field: 'itemNote',title: '备注', visible:false},
            {field: 'itemStr3',title: '挂接状态', formatter: 'statusFormatter'},
            {field: 'itemCreateDate',title: '创建时间',formatter:'createItemAction', visible:false},
            {field: 'action', title: '操作', align: 'center', formatter: 'singleFormatter', events: 'actionEvents', clickToSelect: false}
        ];
        SingleBootstrapTable(url,columns);
    }



    function SingleBootstrapTable(url,columns){
        $table.bootstrapTable({
            url: url,//请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortOrder: "desc",                   //排序方式
            queryParams: "singleItemDefaultParams",
            //queryParams: queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 50,                       //每页的记录行数（*）
            pageList:[50,100],        //可供选择的每页的行数（*）
            //search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            //strictSearch: true,
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            //height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "itemId",                     //每一行的唯一标识，一般为主键列
            //showToggle:true,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            columns: columns,
            onLoadSuccess:function(data){
                //无数据隐藏分页
                if(data && data.total == 0){
                    $('.fixed-table-pagination').hide()
                }
            }
        });

    }

    function singleItemDefaultParams(){
            return {
                sin_itemTitle: $("#txt_volTitle").val(),
                /*volNO: $("#txt_volNO").val(),*/
                sin_itemType:$("#sin_itemType").find(":selected").val(),
                sin_Storagelocation:$("#txt_volStoragelocation").val(),
                limit: params.limit,
                offset: params.offset,
                sort: params.sort,
                order: params.order}
    }

    //格式化密级
    function secretLevelKeepFormatter(value, row, index){
        return secretLevel[value];
    }

    function singleFormatter(value, row, index) {
        return '<a href="javascript:void(0)" style="color:#01579b;" onclick="sinOriAction(' + row.itemId+')" >原文</a>';
    }

    function sinOriAction(sinItemId){
        if(sinItemId !="" && sinItemId !=null){
            $.ajax({
                type: "post",
                url: "${basePath}/pcwindow/sin/viewSinItemOriginal",
                data: { itemId: sinItemId },
                success: function (data) {
                    if (data != "failure") {
                        $('#openPdfModel').modal({
                            keyboard: true
                        });
                        var url=data;
                        var str = url.substr(url.length-4,url.length-1);
                        if(str==".jpg" || str==".png"){
                            var htmlImg = '<img src="'+url+'" style=" width:100%;height: 100%;" alt="预览">';
                            $("#pdfDialog").eq(0).append(htmlImg);
                        }else{
                            var options={
                                pdfOpenParams: {
                                    pagemode: "thumbs",
                                    navpanes: '0',
                                    /*toolbar: '0',*/   //去掉工具栏,打印,下载等,,,,
                                    statusbar: '0',
                                    view: 'FitV'
                                }};
                            var myPDF = PDFObject.embed(url, "#pdfDialog", options);
                        }
                    }else {
                        Ewin.alert("获取原文失败!");
                    }
                },
                error: function () {
                    Ewin.alert('加载错误,请联系管理员!');
                }
            })
        }else{
            Ewin.alert('请选择数据!');
        }
    }

    //加载所有案卷类型
    function findAllJudTypeSiNArch(){
        $.ajax({
            type: "POST",
            url:"${basePath}/pcwindow/findAllJudType",
            dataType:"json",
            async:false,
            success: function(data){
                if (data.length != 0) {
                    var arcTypes = data.rows;
                    var str='<option value="">请选择</option>'
                    for(var i = 0;i < arcTypes.length ;i++){
                        var tyname=arcTypes[i].sortName;
                        var tyid=arcTypes[i].sortNum;
                        str += '<option value="'+ tyid +'">'+ tyname +'</option>'
                    }
                    $('#sin_itemType').html(str);
                }
            }
        });
    }

</script>
</body>
</html>

